package jp.ne.hatena.d.digitalsoul.warikan.actions

import java.io._
import java.text._
import java.util._

import jp.ne.hatena.d.digitalsoul.warikan.contexts._
import jp.ne.hatena.d.digitalsoul.warikan.models._
import jp.ne.hatena.d.digitalsoul.warikan.pages.forms._
import jp.ne.hatena.d.digitalsoul.warikan.pages.items._
import jp.ne.hatena.d.digitalsoul.warikan.repositories._

class AccountingAction extends Serializable {
	
	val format = new SimpleDateFormat("yyyy/MM/dd") 
	
	def createMainFormModel(partyId:Int):AccountingMainForm = {
		
		val mainFormModel = new AccountingMainForm
		
		val party:Party = PartyRepository.forPartyId(partyId)
		mainFormModel.partyName = party.name
		mainFormModel.schedule = format.format(party.schedule)
		mainFormModel.location = party.location
		mainFormModel.sum = party.sum.toString
		
		mainFormModel
	}
	
	
	def createSlopeItems:List[SlopeItem] = {
		
		val slopeItems = new ArrayList[SlopeItem]
		
		SlopeRepository.forAll.foreach { slope =>
			val slopeItem = new SlopeItem
			slopeItem.id = slope.id
			slopeItem.name = slope.name
			slopeItems.add(slopeItem)
		}
		
		slopeItems
	}
	
	
	def calculate(partyId:Int, slopeId:Int, paymentListItems:List[PaymentListItem]) = {
		
		val accounting:Accounting = new Accounting(partyId)
		accounting.adjustBy(slopeId)
		accounting.commit
			
		val party:Party = accounting.party
		val participants = party.participants.values
		participants.foreach { participant =>
			val paymentListItem = new PaymentListItem
			paymentListItem.name = participant.name
			paymentListItem.role = participant.role 
			paymentListItem.payment  = PartyRepository.paymentOf(partyId, participant.name)
			paymentListItems.add(paymentListItem)
		}
	}

}